package com.phpxiu.app.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.phpxiu.app.adapter.ExchangeListAdapter;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.event.OnTicketExchanged;
import com.phpxiu.app.model.event.OnUpdateBalance;
import com.phpxiu.app.model.list.ExchangeContent;
import com.phpxiu.app.model.response.ExchangeListMode;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.VerticalImageSpan;
import com.phpxiu.app.view.custom.WindowLayout;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by WuJinZhou on 2016/6/4.
 */
public class Exchange extends UIBase implements View.OnClickListener {
    public final static String TAG="Exchange";
    public final static String TICKETS_KEY="current_tickets";
    private WindowLayout mainView;
    private long tickets=0;
    private long diamonds=0;
    private List<ExchangeContent>products=new ArrayList<ExchangeContent>();
    private ListView mListView;
    private ExchangeListAdapter mAdapter;
    private View headView;
    private TextView balanceView;
    private VerticalImageSpan icon;
    private SpannableStringBuilder balanceTxt=new SpannableStringBuilder();
    private int balanceTxtColor;
    private OKHttpParam param;
    private String start="";
    private String unit="";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exchange);
        icon=new VerticalImageSpan(this, R.mipmap.diamond_icon);
        mainView=(WindowLayout)findViewById(R.id.exchange_root_view);
        start=getString(R.string.ui_balance_label);
        unit=getString(R.string.ticket_unit);
        tickets=getIntent().getLongExtra(TICKETS_KEY,0L);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        init();
    }

    /**
     * 初始化
     */
    private void init(){
        balanceTxtColor=getResources().getColor(R.color.main_color);
        balanceTxt.clear();
        balanceTxt.append(start).append(" ").append(tickets+"").append(unit+"");
        balanceTxt.setSpan(new ForegroundColorSpan(balanceTxtColor),start.length(),balanceTxt.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        headView= LayoutInflater.from(this).inflate(R.layout.exchange_list_head_view,null);
        headView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        balanceView=(TextView)headView.findViewById(R.id.balance_view);
        balanceView.setText(balanceTxt);
        mListView=(ListView)findViewById(R.id.exchange_list_view);
        mListView.setDivider(null);
        mListView.addHeaderView(headView);
        mAdapter=new ExchangeListAdapter(this,products);
        mAdapter.addClickCallBack(this);
        mListView.setAdapter(mAdapter);
        request();
    }

    /**
     * 请求数据
     */
    private void request(){
        OKHttpParam param=OKHttpParam.builder(false);
        OKHttp.post(HttpConfig.API_EXCHANGE_LIST, param.jsonParam(), TAG, new OKHttpUIHandler(ExchangeListMode.class) {
            @Override
            public void onSuccess(Object model) {
                ExchangeListMode m = (ExchangeListMode) model;
                KKYUtil.log("兑换列表数据：" + m.getResponseStr());
                products.clear();
                products.addAll(m.getData());
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    /**
     * 兑换
     */
    public void onItemClick(final ExchangeContent content){
        if(param==null){
            param=OKHttpParam.builder(false);
        }
        param.put("coin",content.getCoin());
        OKHttp.post(HttpConfig.API_VOTE_EXCHANGE,param.jsonParam(),TAG,new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                try{
                    int coin=Integer.parseInt(content.getCoin());
                    int vote=Integer.parseInt(content.getVote());
                    tickets=tickets-vote;
                    long money= MySelfInfo.getInstance().getMoney();//当前钻石数
                    diamonds=money+coin;//兑换成功后的钻石数据等于当前钻石数加上兑换所得的钻石数
                    balanceTxt.clear();
                    String t=tickets+"";
                    balanceTxt.append(start).append(" ").append(t).append(unit);
                    balanceTxt.setSpan(new ForegroundColorSpan(balanceTxtColor), start.length(), balanceTxt.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    balanceView.setText(balanceTxt);
                    MySelfInfo.getInstance().updateCacheLong(Exchange.this, Constants.USER_MONEY,diamonds);//更新用户钻石数
                    EventBus.getDefault().post(new OnTicketExchanged(false,Long.parseLong(content.getVote())));//通知用户中心刷新票数
                    EventBus.getDefault().post(new OnUpdateBalance(diamonds));//通知各展示余额界面更新余额
                }catch (NumberFormatException e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
            }
        });
    }
}
